package org.test.pong.utils;


import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
/**
 * @ClassName RateLimiter
 * @Description TODO
 * @Author JiaLin
 * @Date 2024/11/21 10:52
 */

public class RateLimiterDiy {
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private long lastRequestTime = 0;

    public RateLimiterDiy() {
        // 启动调度器
        scheduler.scheduleAtFixedRate(() -> {
            lastRequestTime = 0; // 每秒重置请求时间
        }, 1, 1, TimeUnit.SECONDS);
    }

    public synchronized boolean tryInvoke() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastRequestTime >= 1000) {
            lastRequestTime = currentTime;
            return true;
        }
        return false;
    }
}